import {  getCarList,deleteShopping,checkCart } from '@/api'

const state = {
    shoppingcar:[]
}
const mutations={
    GetShoppingCar(state,val){
        state.shoppingcar=val
    }
}
const actions = {
    async getShoppingCar({commit}){
        let result = await getCarList()
        if(result.code=='200'){
            commit('GetShoppingCar',result.data)
        }
    },
    async delShopping({},skuId){
        let result = await deleteShopping(skuId)
        if(result.code==200){
            return 'ok'
        }else{
            return new Promise(Error('请求失败!'))
        }
    },
    async checkShoppingCart({},{skuId,isChecked}){
        let result = await checkCart(skuId,isChecked)
        if(result.code==200){
            return 'ok'
        }else{
            return new Promise(Error('请求失败!'))
        }
    },
    delAll({dispatch,getters}){
        let promises = []
        getters.cartInfo.cartInfoList.forEach(item=>{
          let result = item.isChecked==1?dispatch('delShopping',item.skuId):''
           promises.push(result) 
        })
        return Promise.all(promises)
    },
    checkedAll({dispatch,getters},isCheckAll){
        let promises = []
        getters.cartInfo.cartInfoList.forEach(item=>{
          let result = dispatch('checkShoppingCart',{skuId:item.skuId,isChecked:isCheckAll?1:0})
           promises.push(result) 
        })
        return Promise.all(promises)
    }


}
const getters= {
    cartInfo(state){
        return state.shoppingcar[0]||[]
    },
}
export default {
    namespaced: true,
    state,mutations,actions,getters
}